package com.heima.wemedia.interceptor;

import com.heima.model.wemedia.pojos.WmUser;
import com.heima.wemedia.thread.UserThreadLocal;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.lang.Nullable;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author lzy
 * @date 2022/7/16 17:32
 */
@Slf4j
public class AuthInterceptor implements HandlerInterceptor {

    //前置拦截器
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取请求头上的userid字段
        String userId = request.getHeader("userId");
        if (StringUtils.isEmpty(userId)){
            log.warn("用户id为空");
            return false;
        }

        //2.将userId字段写入到ThreadLocal
        WmUser wmUser = new WmUser();
        wmUser.setId(Integer.parseInt(userId));
        UserThreadLocal.set(wmUser);


        return true;
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
        //清除ThreadLocal，避免内存溢出
        UserThreadLocal.remove();
    }

}
